<?php
namespace Admin\Model;

class AppModel extends \Think\Model
{
	//自动验证
	protected $_validate = array(
			array('app_name', 'require', '请输APP名称',self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
			array('file_id', '/^[1-9]\d*$/', '请输入文件id',self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
			array('platform', '/^\d+$/', '请输入平台类型',self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
			array('update_type', '/^\d+$/', '请输入更新类型',self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
			array('update_status', '/^\d+$/', '请输入更新状态',self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
			array('description', 'require', '请输入app描述信息',self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
			
			//更新
			array('id', '/^\d+$/', '请传入要编辑的记录id', self::MUST_VALIDATE, 'regex', self::MODEL_UPDATE),
	);
	
	//自动完成
	protected $_auto = array(
			array('create_time', 'time', 1, 'function'),
			array('update_time', 'time', 3, 'function'),
			array('status', 0, 1, 'string'),
	);
	
	/**
	 * 添加APP
	 * @param array $data
	 * @author 刘新
	 */
	public function addApp($data)
	{
		//创建数据对象
		if(!$this->create($data)) return array('error' => 1, 'info' => $this->getError());
		
		//查看是否已经存在该本版APP
		$where['api_version'] = $this->api_version;
		$where['app_version'] = $this->app_version;
		$where['platform'] = $this->platform;
		$where['status'] = 1;
		$record = $this->where($where)->find();
		if($record) return array('error' => 1, 'info' => '该版本的APP已经存在');
		
		//添加
		$res = $this->add();
		if($res) return array('error' => 0, 'info' => '添加成功');
		return array('error' => 1, 'info' => '添加失败');
	}

	public function editApp($data)
	{
		//创建数据对象
		if(!$this->create($data)) return array('error' => 1, 'info' => $this->getError());
	
		//查看是否已经存在该本版APP
		$where['api_version'] = $this->api_version;
		$where['app_version'] = $this->app_version;
		$where['platform'] = $this->platform;
		$where['status'] = 1;
		$where['id'] = array('neq', $this->id);
		$record = $this->where($where)->find();
		if($record) return array('error' => 1, 'info' => '该版本的APP已经存在'); 
	
		//添加
		$res = $this->save();
		if($res) return array('error' => 0, 'info' => '编辑成功');
		return array('error' => 1, 'info' => '编辑失败');
	}
}